import { LoginFormData, LoginResponseData, UserInfoResponseData } from '@/api/user/types';
import { UserState } from './types/type';

// 创建用户相关的Store
export const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: routes,
      username: '',
      id: '',
      avatar: '',
    };
  },
  actions: {
    //登录
    async userLogin(data: LoginFormData) {
      const result: LoginResponseData = await reqLogin(data);
      if (result.code === 200) {
        this.token = result.data as string;
        SET_TOKEN(result.data as string);
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },

    //获取用户信息
    async userInfo() {
      const result: UserInfoResponseData = await reqUserInfo();

      if (result.code === 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.id = result.data.id;
        return 'ok';
      } else {
        return Promise.reject('获取用户信息失败');
      }
    },

    //退出登录
    async userLogout() {
      const result: any = await reqLogout();
      if (result.code === 200) {
        this.token = '';
        this.username = '';
        this.avatar = '';
        REMOVE_TOKEN();
        return 'ok';
      } else {
        return Promise.reject(new Error(result.message));
      }
    },
  },
  getters: {},
});
